﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context.Support;
using Project.Manager;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;
using Project.Common;

public class BasePage : System.Web.UI.Page
{
    #region 属性

    public ManagerGather ManagerFactory
    {
        get
        {
            var webApplicationContext = ContextRegistry.GetContext() as WebApplicationContext;
            ManagerGather manager = webApplicationContext.GetObject("ManagerFactory") as ManagerGather;

            return manager;
        }
    }

    /// <summary>
    /// 主键值编辑与查看用
    /// </summary>
    public int SID
    {
        get { int id = 0; int.TryParse(QueryString("id"), out id); return id; }
    }

    /// <summary>
    /// 是否是查看页面.true:是查看页
    /// </summary>
    public bool IsEnable
    {
        get { return !string.IsNullOrEmpty(QueryString("isenable")); }
    }

    /// <summary>
    /// 是否是查看页面.true:是查看页
    /// </summary>
    public string UrlRoot
    {
        get
        {
            string aburl = System.Web.HttpContext.Current.Request.ApplicationPath;
            if (!aburl.EndsWith("/"))
                aburl += "/";
            aburl = System.Web.HttpContext.Current.Request.Url.ToString().Replace(System.Web.HttpContext.Current.Request.Url.PathAndQuery, "") + aburl;
            //if(System.Web.HttpContext.Current.Request.IsLocal)
            //    aburl = aburl.Replace(System.Web.HttpContext.Current.Request.Url.Host,"localhost");
            return aburl;
        }
    }
    #endregion

    #region 登录验证
    /// <summary>
    /// 判断用户是否登录
    /// </summary>
    /// <returns></returns>
    protected bool IsLogin()
    {
        return Page.User.Identity.IsAuthenticated;
    }

    // 检查是否登录，没有登录则跳转到出错页面
    protected void CheckIsLogin()
    {
        if (!IsLogin())
        {
            // 用Session保存需要登录才能访问的页面，以便在登录后可以重定向到该页面
            if (System.Web.HttpContext.Current.Request.Url != null)
            {
                Session["UrlLogonBefore"] = null;
                Session["UrlLogonBefore"] = System.Web.HttpContext.Current.Request.Url.ToString();
            }
            Response.Redirect("~/Home/Login.aspx");
        }
    }
    #endregion

    #region 获取Get,Post参数
    /// <summary>
    /// 获取querystring：简单过滤，以防止SQL注入
    /// </summary>
    /// <param name="s">参数名</param>
    /// <returns>返回值</returns>
    protected string QueryString(string s)
    {
        string result = string.Empty;
        if (System.Web.HttpContext.Current.Request.QueryString[s] != null)
        {
            result = System.Web.HttpContext.Current.Request.QueryString[s].ToString();
            result = FilterSql(result);
        }
        return result;
    }

    /// <summary>
    /// 获取post得到的参数：简单过滤，以防止SQL注入
    /// </summary>
    /// <param name="s">参数名</param>
    /// <returns>返回值</returns>
    protected string FormString(string s)
    {
        string result = string.Empty;
        if (System.Web.HttpContext.Current.Request.Form[s] != null)
        {
            result = System.Web.HttpContext.Current.Request.Form[s].ToString();
            result = FilterSql(result);
        }
        return result;
    }

    private string FilterSql(string result)
    {
        result = result.Replace("'", "&#39;");                // *
        result = result.Replace(";", "；");                   // *

        // 唐海华：加大防止SQL注入的范围
        //str = str.Replace("&", "");
        result = result.Replace("%20", "");                   // *
        result = result.Replace("--", "－－");                // *
        result = result.Replace("==", "＝＝");                // *
        //str = str.Replace("<", "《");
        //str = str.Replace(">", "》");
        //result = result.Replace("%", "％");                   // *
        result = result.Replace("update", "ｕｐｄａｔｅ");    // *

        //str = str.ToLower();

        //str = str.Replace("create", "ｃｒｅａｔｅ");    // *
        //str = str.Replace("select", "ｓｅｌｅｃｔ");    // *
        //str = str.Replace("insert", "ｉｎｓｅｒｔ");    // *
        //str = str.Replace("update", "ｕｐｄａｔｅ");    // *
        ////str = str.Replace("drop", "ｄｒｏｐ");
        ////str = str.Replace("from", "ｆｒｏｍ");
        //str = str.Replace("declare", "ｄｅｃｌａｒｅ"); // *
        result = result.Replace("exec", "ｅｘｅｃ");          // *
        ////str = str..Replace("char", "");
        //str = str.Replace("xp_cmdshell", "");           // *
        //str = str.Replace("where", "ｗｈｅｒｅ");       // *
        //str = str.Replace("or", "ｏｒ");              // * 因为：or在很多词汇中存在
        //str = str.Replace("and", "ａｎｄ");           // - 因为词汇出现的频率高

        result = result.Replace("script", "ｓｃｒｉｐｔ");    // *
        // -----------------------------------------------------  

        return result;
    }
    #endregion

    #region 脚本注册
    /// <summary>
    /// 返回前台一个Alert提示
    /// </summary>
    /// <param name="str">提示信息</param>
    public void Alert(string str)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script language ='javascript'>alert('" + str.Replace("\r\n", "").Replace("'", "\"") + "');</script>");
    }
    /// <summary>
    /// 注册提示信息脚本
    /// </summary>
    /// <param name="alertString">提示信息</param>
    /// <param name="ctl">控件</param>
    public void AlertAjax(string alertString, Control ctl)
    {
        System.Web.UI.ScriptManager.RegisterStartupScript(ctl, ctl.GetType(), "aaaa", "<script language ='javascript'>alert('" + alertString.Replace("\'", "\"").Replace("\r\n", "") + "');</script>", false);
    }
    /// <summary>
    /// 注册提示信息脚本，后执行javascript body
    /// </summary>
    /// <param name="alertString">提示信息</param>
    /// <param name="ctl">控件</param>
    /// <param name="jsBody">javascript body</param>
    public void AlertAjax(string alertString, Control ctl, string jsBody)
    {
        System.Web.UI.ScriptManager.RegisterStartupScript(ctl, ctl.GetType(), "aaaa", "<script language ='javascript'>alert('" + alertString.Replace("\r\n", "").Replace("'", "\"") + "');" + jsBody + ";</script>", false);
    }
    /// <summary>
    /// 注册执行javascript body脚本
    /// </summary>
    /// <param name="jsBody">javascript body</param>
    /// <param name="ctl">控件</param>
    public void ExecJsAjax(string jsBody, Control ctl)
    {
        System.Web.UI.ScriptManager.RegisterStartupScript(ctl, ctl.GetType(), "aaaa", "<script language ='javascript'>" + jsBody + "</script>", false);
    }
    #endregion

    #region 工具
    /// <summary>
    /// Ilist<T> 转换成 DataTable
    /// </summary>
    /// <param name="list"></param>
    /// <param name="IsAddModelName">字段名称前是否添加 类名(主要为了实现将多个类转换成 DataTable)</param>
    /// <returns></returns>
    public DataTable ConvertToDataTable<T>(IList<T> i_objlist, bool IsAddModelName)
    {
        if (i_objlist == null || i_objlist.Count <= 0)
        {
            return null;
        }
        DataTable dt = new DataTable(typeof(T).Name);
        DataColumn column;
        DataRow row;

        System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

        foreach (T t in i_objlist)
        {
            if (t == null)
            {
                continue;
            }
            Type type = t.GetType();

            row = dt.NewRow();

            for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
            {
                System.Reflection.PropertyInfo pi = myPropertyInfo[i];

                string name = IsAddModelName ? type.Name + "_" + pi.Name : pi.Name;

                Type colType = pi.PropertyType;

                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }

                if (dt.Columns[name] == null)
                {
                    column = new DataColumn(name, colType);
                    dt.Columns.Add(column);
                }

                row[name] = pi.GetValue(t, null) == null ? DBNull.Value : pi.GetValue(t, null);
            }

            dt.Rows.Add(row);
        }
        return dt;
    }
    public DataTable ConvertToDataTable<T>(T t)
    {
        IList<T> list = new List<T>();
        list.Add(t);
        return ConvertToDataTable(list, false);
    }
    public DataTable ConvertToDataTable<T>(T t, bool IsAddModelName)
    {
        IList<T> list = new List<T>();
        list.Add(t);
        return ConvertToDataTable(list, IsAddModelName);
    }
    public DataTable ConvertToDataTable<T>(IList<T> i_objlist)
    {
        return ConvertToDataTable<T>(i_objlist, false);
    }
    /// <summary> 
    /// 将两个列不同的DataTable合并成一个新的DataTable 
    /// </summary> 
    /// <param name="dt1">Table表1</param> 
    /// <param name="dt2">Table表2</param> 
    /// <param name="DTName">合并后新的表名</param> 
    /// <returns></returns>
    public DataTable UniteDataTable(DataTable dt1, DataTable dt2, string DTName)
    {
        DataTable dt3 = dt1.Clone();
        for (int i = 0; i < dt2.Columns.Count; i++)
        {
            dt3.Columns.Add(dt2.Columns[i].ColumnName, dt2.Columns[i].DataType);
        }
        object[] obj = new object[dt3.Columns.Count];

        for (int i = 0; i < dt1.Rows.Count; i++)
        {
            dt1.Rows[i].ItemArray.CopyTo(obj, 0);
            dt3.Rows.Add(obj);
        }

        if (dt1.Rows.Count >= dt2.Rows.Count)
        {
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                for (int j = 0; j < dt2.Columns.Count; j++)
                {
                    if (dt2.Rows[i][j] != null && !string.IsNullOrEmpty(dt2.Rows[i][j].ToString()))
                        dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                }
            }
        }
        else
        {
            DataRow dr3;
            for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++)
            {
                dr3 = dt3.NewRow();
                dt3.Rows.Add(dr3);
            }
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                for (int j = 0; j < dt2.Columns.Count; j++)
                {
                    dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                }
            }
        }
        dt3.TableName = DTName;
        return dt3;
    }
    public DataTable UniteDataTable(DataTable dt1, DataTable dt2)
    {
        return UniteDataTable(dt1, dt2, dt1.TableName);
    }

    #endregion

    #region 绑定页面控件与对象的值

    /// <summary>
    /// 绑定页面控件与对象的值
    /// 此处不检查控件中的值是否是正确的类型,数据类型应该通过 Page.IsValid 检查
    /// </summary>
    /// <param name="controls">页面控件集合</param>
    /// <param name="t">对象类型</param>
    /// <param name="IsViewState">true:查看页面,将 t 中的数据还原到页面中.false:保存状态:将控件中的值保存到 t 中</param>
    /// <returns>只有在 IsViewState = false:保存状态的时候才有用</returns>
    internal T BindControlsValue<T>(ControlCollection controls, T t, bool IsViewState)
    {
        foreach (Control ctrl in controls)
        {
            #region 变量
            // 实行名称
            string field = ctrl.GetField();
            // 是否允许为空
            bool isNull = ctrl.GetIsNull();
            // 
            string notice = ctrl.GetNotice();
            string dbtype = ctrl.GetDbType();
            bool IsSingleCheckBox = ctrl.GetIsSingleCheckBox();
            string dateFormat = this.GetAttributes(ctrl, "DateFormat");
            #endregion

            // field 和 dbtype 都不能为空
            if (!string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(dbtype))
            {
                PropertyInfo pi = t.GetType().GetProperty(field);
                // 判断 field 是否是 t 的属性
                if (pi != null)
                {
                    if (IsViewState)
                    {
                        // 查看页面,将 t 中的数据还原到页面中
                        #region 查看状态

                        object obj = pi.GetValue(t, null);
                        string value = string.Empty;
                        if (obj != null)
                        {
                            value = obj.ToString().Trim();

                            #region 数据格式化
                            if (dbtype.ToLower() == "DateTime".ToLower() && !string.IsNullOrEmpty(dateFormat))
                            {
                                value = DateTime.Parse(value).ToString(dateFormat);
                            }
                            #endregion
                        }

                        switch (ctrl.ToString())
                        {
                            case "System.Web.UI.WebControls.Label":
                                ((Label)ctrl).Text = value;
                                break;
                            case "System.Web.UI.WebControls.TextBox":
                                ((TextBox)ctrl).Text = value;
                                break;
                            case "System.Web.UI.WebControls.DropDownList":
                                if (((DropDownList)ctrl).Items.FindByValue(value) != null)
                                {
                                    ((DropDownList)ctrl).ClearSelection();
                                    ((DropDownList)ctrl).Items.FindByValue(value).Selected = true;
                                }
                                break;
                            case "System.Web.UI.WebControls.RadioButtonList":
                                if (((RadioButtonList)ctrl).Items.FindByValue(value) != null)
                                {
                                    ((RadioButtonList)ctrl).ClearSelection();
                                    ((RadioButtonList)ctrl).Items.FindByValue(value).Selected = true;
                                }
                                break;
                            case "System.Web.UI.WebControls.CheckBox":
                                ((CheckBox)ctrl).Checked = value == "1";
                                break;
                            case "System.Web.UI.WebControls.CheckBoxList":
                                // 这里要区分 是多选还是单选
                                if (IsSingleCheckBox)
                                {
                                    // 单选
                                    if (((CheckBoxList)ctrl).Items.FindByValue(value) != null)
                                    {
                                        ((CheckBoxList)ctrl).ClearSelection();
                                        ((CheckBoxList)ctrl).Items.FindByValue(value).Selected = true;
                                    }
                                }
                                else
                                {
                                    // 多选
                                    // 多选采用与或的方式进行比较
                                    throw new SystemException("还没有实现相应的方法");
                                }
                                break;
                        }
                        #endregion
                    }
                    else
                    {
                        // 保存状态:将控件中的值保存到 t 中
                        #region 保存状态

                        object objValue = new object();
                        switch (ctrl.ToString())
                        {
                            case "System.Web.UI.WebControls.Label":
                                continue;
                            //objValue = ((Label)ctrl).Text.Trim();
                            //break;
                            case "System.Web.UI.WebControls.TextBox":
                                objValue = ((TextBox)ctrl).Text.Trim();
                                break;
                            case "System.Web.UI.WebControls.DropDownList":
                                objValue = ((DropDownList)ctrl).SelectedValue;
                                break;
                            case "System.Web.UI.WebControls.RadioButtonList":
                                objValue = ((RadioButtonList)ctrl).SelectedValue;
                                break;
                            case "System.Web.UI.WebControls.CheckBox":
                                objValue = ((CheckBox)ctrl).Checked ? "1" : "0";
                                break;
                            case "System.Web.UI.WebControls.CheckBoxList":
                                // 这里要区分 是多选还是单选
                                if (IsSingleCheckBox)
                                {
                                    // 单选
                                    objValue = ((CheckBoxList)ctrl).SelectedValue;
                                }
                                else
                                {
                                    // 多选
                                    // 多选采用与或的方式进行比较
                                    throw new SystemException("还没有实现相应的方法");
                                }
                                break;
                        }

                        if (string.IsNullOrEmpty(objValue.ToString()) && isNull)
                        {
                            objValue = null;
                        }

                        #region 获取数据类型对应的 类名
                        switch (dbtype.ToLower())
                        {
                            case "string":
                                dbtype = typeof(String).FullName;
                                break;
                            case "int":
                                dbtype = typeof(Int32).FullName;
                                break;
                            case "double":
                                dbtype = typeof(Double).FullName;
                                break;
                            case "datetime":
                                dbtype = typeof(DateTime).FullName;
                                break;
                            case "byte":
                                dbtype = typeof(Byte).FullName;
                                break;
                        }

                        #endregion

                        Type type = Type.GetType(dbtype);
                        Type[] types = new Type[1];
                        types[0] = typeof(String);
                        MethodInfo m = type.GetMethod("Parse", types);
                        if (m != null && objValue != null && !string.IsNullOrEmpty(objValue.ToString()))
                        {
                            Object[] parameters = new Object[1];
                            parameters[0] = objValue;
                            objValue = m.Invoke(null, parameters);
                        }
                        pi.SetValue(t, objValue, null);

                        #endregion
                    }
                }
            }
        }
        return t;
    }

    public string GetAttributes(Control control, string attributesName)
    {
        string value = string.Empty;
        PropertyInfo pi = control.GetType().GetProperty("Attributes");
        if (pi != null)
        {
            value = ((AttributeCollection)pi.GetValue(control, null))[attributesName];
        }
        return value;
    }

    #endregion

    #region 页面元素控件绑定
    /// <summary>
    /// 通过数组进行页面控件绑定
    /// </summary>
    /// <param name="cbl">绑定类型</param>
    /// <param name="strings">数组数据源</param>
    /// <param name="IsIndex">控件中的Value是否为数值还是相同的值（true：value=数字；false：value=text）</param>
    /// <param name="index">从第几个索引开始绑定</param>
    /// <param name="repeatColumns">要在 CheckBoxList 控件中显示的列数</param>
    public void BindStrings2WebControls(CheckBoxList cbl, string[] strings, bool IsIndex, int index)
    {
        ListItemCollection items = new ListItemCollection();

        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
                items.Add(new ListItem(strings[i], i.ToString()));
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        cbl.DataSource = items;
        cbl.DataTextField = "text";
        cbl.DataValueField = "value";
        cbl.DataBind();
        cbl.RepeatColumns = cbl.Items.Count;
        cbl.TextAlign = TextAlign.Left;
    }
    public void BindStrings2WebControls(RadioButtonList rbl, string[] strings, bool IsIndex, int index)
    {
        ListItemCollection items = new ListItemCollection();

        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
                items.Add(new ListItem(strings[i], i.ToString()));
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        rbl.DataSource = items;
        rbl.DataTextField = "text";
        rbl.DataValueField = "value";
        rbl.DataBind();
        rbl.RepeatColumns = rbl.Items.Count;		// 默认为水平方向
        rbl.TextAlign = TextAlign.Left;				// 默认文字居左
        //rbl.Items[0].Selected = true;				// 默认第一个选项被选中，防止用户不选择时，保存出错
    }
    public void BindStrings2WebControls(DropDownList ddl, string[] strings, bool IsIndex, int index)
    {
        ListItemCollection items = new ListItemCollection();

        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
                items.Add(new ListItem(strings[i], i.ToString()));
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        ddl.DataSource = items;
        ddl.DataTextField = "text";
        ddl.DataValueField = "value";
        ddl.DataBind();
        ddl.ClearSelection();
    }

    /// <summary>
    /// 通过Enum进行页面控件绑定
    /// </summary>
    /// <param name="cbl">绑定类型</param>
    /// <param name="Type">Enum数据源</param>
    /// <param name="IsIndex">控件中的Value是否为数值还是相同的值（true：value=Enum中对应的值；false：value=text）</param>
    /// <param name="index">从第几个索引开始绑定</param>
    /// <param name="repeatColumns">要在 CheckBoxList 控件中显示的列数</param>
    public void BindEnum2WebControls(CheckBoxList cbl, Type enumStr, bool IsIndex, int index, int repeatColumns)
    {
        ListItemCollection items = new ListItemCollection();

        string[] strings = Enum.GetNames(enumStr);
        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
            {
                // 修正，value 应该是枚举中的值而不是索引
                //items.Add(new ListItem(strings[i], i.ToString()));
                items.Add(new ListItem(strings[i], ((int)Enum.Parse(enumStr, strings[i])).ToString()));
            }
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        cbl.DataSource = items;
        cbl.DataTextField = "text";
        cbl.DataValueField = "value";
        cbl.DataBind();
        cbl.RepeatColumns = repeatColumns == 0 ? cbl.Items.Count : repeatColumns;
        cbl.RepeatDirection = RepeatDirection.Horizontal;
        cbl.TextAlign = TextAlign.Left;
    }
    public void BindEnum2WebControls(RadioButtonList rbl, Type enumStr, bool IsIndex, int index)
    {
        ListItemCollection items = new ListItemCollection();

        string[] strings = Enum.GetNames(enumStr);
        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
            {
                // 修正，value 应该是枚举中的值而不是索引
                //items.Add(new ListItem(strings[i], i.ToString()));
                items.Add(new ListItem(strings[i], ((int)Enum.Parse(enumStr, strings[i])).ToString()));
            }
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        rbl.DataSource = items;
        rbl.DataTextField = "text";
        rbl.DataValueField = "value";
        rbl.DataBind();

        rbl.RepeatColumns = rbl.Items.Count;
        rbl.TextAlign = TextAlign.Left;
    }
    public void BindEnum2WebControls(DropDownList ddl, Type enumStr, bool IsIndex, int index)
    {
        ListItemCollection items = new ListItemCollection();

        string[] strings = Enum.GetNames(enumStr);
        for (int i = index; i < strings.Length; i++)
        {
            if (IsIndex)
            {
                // 修正，value 应该是枚举中的值而不是索引
                //items.Add(new ListItem(strings[i], i.ToString()));
                items.Add(new ListItem(strings[i], ((int)Enum.Parse(enumStr, strings[i])).ToString()));
            }
            else
                items.Add(new ListItem(strings[i], strings[i]));
        }

        ddl.DataSource = items;
        ddl.DataTextField = "text";
        ddl.DataValueField = "value";
        ddl.DataBind();
    }
    #endregion

    /// <summary>
    /// 是否发送短信 在 web.config 中设置
    /// </summary>
    protected bool IsSendSMS { get { string _SendSMS = System.Configuration.ConfigurationManager.AppSettings["IsSendSMS"]; bool _IsSendSMS = false; _IsSendSMS = (!string.IsNullOrEmpty(_SendSMS) && _SendSMS.ToLower() == "true".ToLower()) ? true : false; return _IsSendSMS; } }

    /// <summary>
    /// 调用 webservices 短信接口发送短信
    /// </summary>
    /// <param name="mobileNo"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    public object SendSMS(string mobileNo, string content)
    {
        //string url = "http://www.webservicex.net/globalweather.asmx"
        string url = System.Configuration.ConfigurationManager.AppSettings["SMSServices"];
        if (string.IsNullOrEmpty(url))
        {
            Alert("请先添加 短信服务接口地址!");
        }
        string[] args = new string[2];
        args[0] = mobileNo;
        args[1] = content;
        object result = WebServiceHelper.InvokeWebService(url, "SentMsg", args);
        return result;

    }
}

/// 这是C# 3.0(.NET Framework 3.5)新增的一个伟大特性，在此之前在C#中想要为内置类型添加一个自定义方法几乎不可能，
/// 但现在，在C# 3.0变得非常的简单。
/// 例如，我们为int类型添加一个平方的方法，为string类型添加一个ToInt32方法： 
/// 非常简单，先定义一个静态类，在类中实现我们的扩展方法：
/// http://xfrog.blogbus.com/logs/57498701.html
/// <summary>
/// C#中为内置类型添加扩展方法
/// </summary>
public static class ExternClass
{
    /// <summary>
    /// 平方
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    public static Int64 Square(this Int32 i)
    {
        return i * i;
    }
    /// <summary>
    /// 开方
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static Int32 ToInt32(this string s)
    {
        return Int32.Parse(s);
    }

    //<asp:TextBox newfield="Sender" newtype="string" notice="Sender" null="True" />
    /// <summary>
    /// 对应的数据库中表的字段名称
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string GetField(this Control s)
    {
        PropertyInfo pi = s.GetType().GetProperty("Attributes");
        if (pi != null)
            return ((AttributeCollection)pi.GetValue(s, null))["newfield"];
        else
            return string.Empty;
    }
    /// <summary>
    /// 对应数据库中表的字段是否为空
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool GetIsNull(this Control s)
    {
        PropertyInfo pi = s.GetType().GetProperty("Attributes");
        if (pi != null && ((AttributeCollection)pi.GetValue(s, null))["null"] != null)
            return ((AttributeCollection)pi.GetValue(s, null))["null"].ToLower() == "true";
        else
            return false;
    }
    /// <summary>
    /// 针对于 CheckBoxList 控件是否是单选.true:单选.false:多选
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool GetIsSingleCheckBox(this Control s)
    {
        PropertyInfo pi = s.GetType().GetProperty("Attributes");
        if (pi != null && ((AttributeCollection)pi.GetValue(s, null))["IsSingleCheckBox"] != null)
            return ((AttributeCollection)pi.GetValue(s, null))["IsSingleCheckBox"].ToLower() == "true";
        else
            return false;
    }
    /// <summary>
    /// 对应数据库中表的字段的中文名称(描述)
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string GetNotice(this Control s)
    {
        PropertyInfo pi = s.GetType().GetProperty("Attributes");
        if (pi != null)
            return ((AttributeCollection)pi.GetValue(s, null))["Notice"];
        else
            return string.Empty;
    }
    /// <summary>
    /// 对应数据库中表的字段类型,必须是 SqlDbType 类型
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string GetDbType(this Control s)
    {
        //return Enum.Parse(typeof(SqlDbType), s.Attributes["newtype"]).ToString();
        PropertyInfo pi = s.GetType().GetProperty("Attributes");
        if (pi != null)
            return ((AttributeCollection)pi.GetValue(s, null))["newtype"];
        else
            return string.Empty;
    }

}